﻿using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Mail;

/// <summary>
/// Summary description for LogErro
/// </summary>
public static class Log
{
    /// <summary>
    /// Escreve no arquivo /log/log.txt os erros apresentados nas páginas
    /// </summary>
    /// <param name="ex">A exceção</param>
    /// <param name="obs">Página -> método que originou o erro</param>
    public static void Write(Exception ex, string obs)
    {
        try
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("#################################################");
            sb.AppendLine(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + "| Método: " + obs + " | Erro: " + ex.Message);
            sb.AppendLine("Stack Trace:");
            sb.AppendLine(ex.StackTrace);
            sb.AppendLine("# end of stack trace");
            sb.AppendLine("#################################################");
            File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"log/log.txt", sb.ToString());
        }
        catch(Exception exce)
        {
            SendEmail(exce);
        }
    }

    private static void SendEmail(Exception ex)
    {
        SmtpClient cliente = new SmtpClient("smtp.gmail.com", 587 /* TLS */);
        cliente.EnableSsl = true;

        StringBuilder sb = new StringBuilder();
        sb.AppendLine(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + "| Erro: " + ex.Message);
        sb.AppendLine("Stack Trace:");
        sb.AppendLine(ex.StackTrace);
        sb.AppendLine("# end of stack trace");        

        MailMessage mensagem = new MailMessage("arthursouza@dadosturbelem.com", "contato@dadosturbelem.com", "DadosTur - Erro no sistema", sb.ToString());
        mensagem.To.Add("arthur.souza99@gmail.com");

        NetworkCredential credenciais = new NetworkCredential(
          "contato@dadosturbelem.com", /* login */
          "S@L@M@nder", /* senha */
          "");

        cliente.Credentials = credenciais;
        cliente.Send(mensagem);
    }

    public static void Write(string query)
    {
        try
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("###");
            sb.AppendLine(query);
            sb.AppendLine("###");
            File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + @"/log/queries" + DateTime.Now.ToString("yyyyMMdd") + ".txt", sb.ToString());
        }
        catch(Exception ex)
        {
            Log.Write(ex, "Erro ao escrever query");
        }
    }
}
